package gov.kqqzyyy.monkey.orderpad.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DownloadManager;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.android.material.textfield.TextInputEditText;
import com.socks.library.KLog;

import java.util.Date;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import gov.kqqzyyy.monkey.orderpad.R;
import gov.kqqzyyy.monkey.orderpad.broadcastreceiver.DownLoadReceiver;
import gov.kqqzyyy.monkey.orderpad.broadcastreceiver.UpdateReceiver;
import gov.kqqzyyy.monkey.orderpad.mytools.CurrentVersion;
import gov.kqqzyyy.monkey.orderpad.mytools.DateTimeUtil;
import gov.kqqzyyy.monkey.orderpad.network.RetrofitUtil;
import gov.kqqzyyy.monkey.orderpad.network.base.BaseObserver;
import gov.kqqzyyy.monkey.orderpad.network.bean.BaseResponse;
import gov.kqqzyyy.monkey.orderpad.object.XTGL;
import gov.kqqzyyy.monkey.orderpad.object.post_param.UserLoginParam;
import gov.kqqzyyy.monkey.orderpad.service.UpdateService;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


@SuppressLint("NonConstantResourceId")
public class UserLoginActivity extends NavigationBaseActivity implements View.OnClickListener {

    @BindView(R.id.container)
    FrameLayout container;
    TextInputEditText account_inputText;
    TextInputEditText passwd_inputText;
    TextView versionText, wifiStatusText;
    Button loginBtn, jscBtn, oscBtn;

    private long firstTime = 0;

    private final Handler myHandler = new Handler();
    private final Runnable mLoadingRunnable = this::loadView;

    private Intent serviceIntent;
    private UpdateReceiver updateReceiver;
    private DownLoadReceiver downLoadReceiver;

    private static final int REQUESTPERMISSION = 110;

    private boolean ableToChangeWIFI = false;

    private BaseObserver<XTGL> loginObserver;
    private BaseObserver<String> systemTimeObserver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);

        serviceIntent = new Intent(getApplicationContext(), UpdateService.class);
        downLoadReceiver = new DownLoadReceiver();
        IntentFilter downLoadFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        registerReceiver(downLoadReceiver, downLoadFilter);
        updateReceiver = new UpdateReceiver(this);
        IntentFilter updateFilter = new IntentFilter("updatebroadcast");
        registerReceiver(updateReceiver, updateFilter);

        initGPS();
    }

    private void loadView() {
        container.removeAllViews();
        LayoutInflater.from(this).inflate(R.layout.activity_user_login, container);
        onBindUI();

        loginBtn.setOnClickListener(this);
        jscBtn.setOnClickListener(this);
        oscBtn.setOnClickListener(this);

        String account = getMySharedPreferences().getString("account", "");
        account_inputText.setText(account);
        passwd_inputText.setText("");
        if (!Objects.requireNonNull(account).equals("")) {
            passwd_inputText.requestFocus();
        }
        doSetVersion();
    }

    @Override
    protected void onResume() {
        super.onResume();
        doStartService();
        //延时加载页面，减少打开等待时间
        getWindow().getDecorView().post(() -> myHandler.post(mLoadingRunnable));
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (loginObserver != null) {
            loginObserver.doCancelRequest();
        }
        if (systemTimeObserver != null) {
            systemTimeObserver.doCancelRequest();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(downLoadReceiver);
        unregisterReceiver(updateReceiver);
        System.gc();
    }

    public void doStartService() {
        //检查权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.CHANGE_WIFI_STATE) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CHANGE_WIFI_STATE
            }, REQUESTPERMISSION);
        } else {
            ableToChangeWIFI = true;
            startService(serviceIntent);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUESTPERMISSION) {
            if (permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (serviceIntent != null) {
                        startService(serviceIntent);
                    }
                } else {//提示没有权限，安装不了咯
                    showToast("没有存储读写权限，无法进行更新！");
                }
            }
            if (permissions[1].equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
                if (grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    ableToChangeWIFI = true;
                } else {
                    showToast("没有权限，请打开位置信息");
                }
            }
            if (permissions[2].equals(Manifest.permission.CHANGE_WIFI_STATE)) {
                if (grantResults[2] == PackageManager.PERMISSION_GRANTED) {
                    ableToChangeWIFI = true;
                } else {
                    showToast("没有权限，无法一键切换WIFI");
                }
            }
        }
    }

    private void onBindUI() {
        account_inputText = findViewById(R.id.userlogin_input_account);
        passwd_inputText = findViewById(R.id.userlogin_input_password);
        loginBtn = findViewById(R.id.userlogin_btn);
        jscBtn = findViewById(R.id.jsc_btn);
        oscBtn = findViewById(R.id.osc_btn);
        versionText = findViewById(R.id.version_text);
        wifiStatusText = findViewById(R.id.wifi_status_textview);
        setWifiInfoTextView(wifiStatusText);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.userlogin_btn:
                String account = Objects.requireNonNull(account_inputText.getText()).toString();
                String passwd = Objects.requireNonNull(passwd_inputText.getText()).toString();
                if (account.equals("")) {
                    Toast.makeText(getApplicationContext(), "请输入工号！", Toast.LENGTH_SHORT).show();
                } else {
                    doLoginTest(account, passwd);
                }
                break;
            case R.id.jsc_btn:
                if (ableToChangeWIFI) {
                    connectWIFI(1);
                }
                break;
            case R.id.osc_btn:
                if (ableToChangeWIFI) {
                    connectWIFI(2);
                }
                break;
        }
    }

//    @Override
//    public void setWIFIInfo(String info) {
//        super.setWIFIInfo(info);
//        if (wifiStatusText != null && info != null) {
//            String result = getString(R.string.login_text_4) + info;
//            wifiStatusText.setText(result);
//        } else {
//            new Handler().postDelayed(() -> setWIFIInfo(info), 1000);
//        }
//    }

    private void doLoginTest(String account, String passwd) {
        showProgressDialog("登陆中");
        UserLoginParam param = new UserLoginParam(account, passwd);
        Observable<BaseResponse<XTGL>> observable = RetrofitUtil.getInstence().doLogin(param);
        loginObserver = new BaseObserver<XTGL>() {
            @Override
            protected void onSuccees(BaseResponse<XTGL> t) {
                cancelProgressDialog();
                getMyApplication().setXtgl(t.getData());
                getMySharedPreferences().edit().putString("account", account).apply();
                Intent intent = new Intent(getApplicationContext(), OrderMenuActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
            }

            @Override
            protected void onFailure(Throwable e, boolean isNetWorkError) {
                cancelProgressDialog();
                KLog.d("APE", "登陆失败：" + e);
                showToast("登陆失败：" + e.getMessage());
            }

            @Override
            protected void onCodeError(BaseResponse<XTGL> t) {
                super.onCodeError(t);
                cancelProgressDialog();
                KLog.d("APE", "登陆失败\n错误代码：" + t.getCode() + "\n错误信息：" + t.getMsg());
                showToast("登陆失败\n错误代码：" + t.getCode() + "\n错误信息：" + t.getMsg());
            }

        };
        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(loginObserver);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                firstTime = secondTime;
                return true;
            } else {
                System.exit(0);
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    public void doSetVersion() {
        String text = "版本号：" + CurrentVersion.getVerName(this);
        if (versionText != null) {
            versionText.setText(text);
        }
        doGetSystemTime();
    }

    private void doGetSystemTime() {
//        KLog.d("APE", "getSystemTime");
        Observable<BaseResponse<String>> observable = RetrofitUtil.getInstence().getSystemTime();
        systemTimeObserver = new BaseObserver<String>() {
            @Override
            protected void onSuccees(BaseResponse<String> t) {
                String serverTime = t.getData().replace("T", " ");
                Date serverDate = DateTimeUtil.getDTFormatDateTime(serverTime);
                if (serverDate != null) {
                    long deleta = serverDate.getTime() - new Date(System.currentTimeMillis()).getTime();
                    getMyApplication().setDeleta(deleta);
                    KLog.d("APE", "同步服务器世界成功！");
                }
            }

            @Override
            protected void onFailure(Throwable e, boolean isNetWorkError) {
                cancelProgressDialog();
                KLog.d("APE", "获取系统时间失败：" + e);
            }

            @Override
            protected void onCodeError(BaseResponse<String> t) {
                super.onCodeError(t);
                KLog.d("APE", t);
            }

        };
        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(systemTimeObserver);
    }

    // 更新提示对话框
    public void showUpdateDialog(int newVerCode, String newVerName, String updateInfo) {
        cancelProgressDialog();
        String message = "";
        final Intent intent = new Intent("toUpdateService");
        message += "发现新版本：" + newVerName + "\n";
        message += "版本号：" + newVerCode + "\n";
        message += "更新内容：" + updateInfo + "\n";
        message += "是否更新？";
        Dialog dialog = new AlertDialog.Builder(this)
                .setTitle("软件更新")
                .setMessage(message)
                .setCancelable(false)
                .setPositiveButton("确定", (dialogInterface, i) -> {
                    intent.putExtra("toservice", 0x11);
                    sendBroadcast(intent);
                    dialogInterface.dismiss();
                    showProgressDialog("下载中");
                })
                .setNegativeButton("取消", (dialogInterface, i) -> dialogInterface.dismiss())
                .create();
        dialog.show();
    }

}
